//
//  KHHPlayViewController.m
//  Travel
//
//  Created by dllo on 15/12/5.
//  Copyright © 2015年 doll. All rights reserved.
//

#import "KHHPlayViewController.h"
#import "STKAudioPlayer.h"
#import <QuartzCore/CoreAnimation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <CFNetwork/CFNetwork.h>
#import "UIImageView+WebCache.h"

@interface KHHPlayViewController ()

@property (nonatomic, retain) UIImageView *imgView;
@property (nonatomic, retain) UIButton *playButton;
@property (nonatomic, retain) UIButton *pauseButton;
@property (nonatomic, retain) UIButton *stopButton;
@property (nonatomic, retain) UIButton *nextButton;
@property (nonatomic, retain) UIButton *backButton;
@property (nonatomic, retain) UILabel *timeLabelstart;
@property (nonatomic, retain) UILabel *timeLabelend;
@property (nonatomic, retain) UISlider *progressSlider;
@property (nonatomic, retain) NSTimer *timer;
@property (nonatomic, retain) STKAudioPlayer *audioPlayer;

@end

@implementation KHHPlayViewController

+ (instancetype)ShareKHHPlayerViewController
{
    static KHHPlayViewController *play = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        play = [[KHHPlayViewController alloc] init];
    });
    return play;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.audioPlayer dispose]; // 销毁player
    [self createAudioPlayer]; // 创建player
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = self.model.title;
    
    // 图片
    self.imgView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 70, WIDTH - 20, 350)];
    [self.imgView sd_setImageWithURL:[NSURL URLWithString:self.model.coverLarge]];
    [self.view addSubview:self.imgView];
    
    // 播放按钮
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playButton.frame = CGRectMake(WIDTH / 2.0 - 35, 485, 60, 60);
    self.playButton.backgroundColor = [UIColor orangeColor];
    self.playButton.layer.masksToBounds = YES;
    self.playButton.layer.cornerRadius = 30;
   // [self.playButton setTitle:@"暂停" forState:UIControlStateNormal];
    [self.playButton setImage:[UIImage imageNamed:@"0012.jpg"] forState:UIControlStateNormal];
    [self.playButton addTarget:self action:@selector(playAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.playButton];
    
//    // 暂停按钮
//    self.pauseButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.pauseButton.frame = CGRectMake(375/ 2.0 +10, 500, 60, 30);
//    self.pauseButton.backgroundColor = [UIColor orangeColor];
//    [self.pauseButton setTitle:@"暂停" forState:UIControlStateNormal];
//    [self.pauseButton addTarget:self action:@selector(pause) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:self.pauseButton];
    
    // 停止按钮
    self.stopButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.stopButton.frame = CGRectMake(WIDTH - 70, 90, 40, 40);
    //self.stopButton.backgroundColor = [UIColor orangeColor];
    //[self.stopButton setTitle:@"停止" forState:UIControlStateNormal];
   // [self.stopButton setImage:[UIImage imageNamed:@"040.jpg"] forState:UIControlStateNormal];
    self.stopButton.layer.masksToBounds = YES;
    self.stopButton.layer.cornerRadius = 20;
   // [self.stopButton addTarget:self action:@selector(stopAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.stopButton];
    
    // 下一首
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextButton.frame = CGRectMake(WIDTH - 130, 490, 50, 50);
    self.nextButton.backgroundColor = [UIColor orangeColor];
    self.nextButton.layer.masksToBounds = YES;
    self.nextButton.layer.cornerRadius = 25;
   // [self.nextButton setTitle:@"下一首" forState:UIControlStateNormal];
    [self.nextButton setImage:[UIImage imageNamed:@"03500.jpg"] forState:UIControlStateNormal];
    [self.nextButton addTarget:self action:@selector(nextAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.nextButton];
    
    // 上一首
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backButton.frame = CGRectMake(70, 490, 50, 50);
    self.backButton.backgroundColor = [UIColor orangeColor];
    self.backButton.layer.masksToBounds = YES;
    self.backButton.layer.cornerRadius = 25;
    //[self.backButton setTitle:@"上一首" forState:UIControlStateNormal];
    [self.backButton setImage:[UIImage imageNamed:@"0300.jpg"] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backButton];
    
    //开始时间
    self.timeLabelstart =[[UILabel alloc] initWithFrame:CGRectMake(5, 440, 50, 23)];
   // self.timeLabelstart.backgroundColor = [UIColor lightGrayColor];
    self.timeLabelstart.font = [UIFont systemFontOfSize:14];
    self.timeLabelstart.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.timeLabelstart];
    
    //结束时间
    self.timeLabelend =[[UILabel alloc] initWithFrame:CGRectMake(WIDTH - 55, 440, 50, 23)];
    self.timeLabelend.font = [UIFont systemFontOfSize:14];
    self.timeLabelend.textAlignment = NSTextAlignmentCenter;
   // self.timeLabelend.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:self.timeLabelend];
    
    //进度条
    self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(55, 440, WIDTH - 110, 23)];
    [self.progressSlider addTarget:self action:@selector(progressSlider:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.progressSlider];
    
    
}

- (void)progressSlider:(UISlider *)sender {
    
    if (self.audioPlayer) {
        
        [self.audioPlayer seekToTime:sender.value];
        
    }
}


//创建AudioPlayer
- (void)createAudioPlayer
{
    /*
     “STKAudioPlayer”类队列管理和显示音频从一个数据源。默认情况下“STKAudioPlayer”会自动解析url并在内部创建适当的数据源。
     
     (STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }
     是结构体赋值
     */
    
    
    self.audioPlayer.volume = 2;
    
    [self.audioPlayer play:self.model.playUrl64]; // 播放url音频\
    
    //调用定时器方法
    [self createTimer];
}

//创建定时器
- (void)createTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
}

//关闭定时器
- (void)closeTimer
{
    if (self.timer.valid) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

//定时器方法
- (void)timeAction
{
        self.progressSlider.maximumValue = self.audioPlayer.duration;//音乐总共时长
        self.progressSlider.value = self.audioPlayer.progress;//当前进度
        // 如果当前歌曲播放完毕自动播放下一首
        if(self.progressSlider.value == self.progressSlider.maximumValue){
            if (self.indexRow == self.allMusicArray.count) {
    
                self.indexRow = 0;
            }
    
            [self.audioPlayer play:[self.allMusicArray[self.indexRow++] playUrl64]];
        }
    
    NSInteger proMin = (NSInteger)self.audioPlayer.progress / 60;
    NSInteger proSec = (NSInteger)self.audioPlayer.progress % 60;
    NSInteger durMin = (NSInteger)self.audioPlayer.duration / 60;
    NSInteger durSec = (NSInteger)self.audioPlayer.duration % 60;
    
    [self.timeLabelstart setText:[NSString stringWithFormat:@"%02ld:%02ld",proMin,proSec]];
    [self.timeLabelend setText:[NSString stringWithFormat:@"%02ld:%02ld",durMin,durSec]];
    //    NSLog(@"%@" , self.timeLabel.text);
}


- (void)playAction
{
    if (self.audioPlayer.state == STKAudioPlayerStatePaused) {
        
       // [self.playButton setTitle:@"暂停" forState:UIControlStateNormal];
        [self.playButton setImage:[UIImage imageNamed:@"0012.jpg"] forState:UIControlStateNormal];
        [self.audioPlayer resume];// 继续
        [self createTimer];
        // NSLog(@"播放");
    }
    else if (self.audioPlayer.state == STKAudioPlayerStatePlaying)
    {
        //[self.playButton setTitle:@"播放" forState:UIControlStateNormal];
        [self.playButton setImage:[UIImage imageNamed:@"02300.jpg"] forState:UIControlStateNormal];
        [self.audioPlayer pause];
        [self closeTimer];
       // NSLog(@"暂停");
    }
    else if (self.audioPlayer.state == STKAudioPlayerStateStopped){
    [self.audioPlayer play:self.model.playUrl64];
    }

}

- (void)stopAction
{
    [self.audioPlayer stop];
    [self.audioPlayer clearQueue];//清空音频队列
    [self.playButton setTitle:@"播放" forState:UIControlStateNormal];
    
}

- (void)nextAction
{
    self.indexRow++;
    if (self.indexRow == self.allMusicArray.count) {
        self.indexRow = 0;
    }
    self.navigationItem.title = [self.allMusicArray[self.indexRow] title];
    [self.imgView sd_setImageWithURL:[NSURL URLWithString:[self.allMusicArray[self.indexRow] coverLarge]]];
    [self.audioPlayer play:[self.allMusicArray[self.indexRow] playUrl64]];
    [self.playButton setImage:[UIImage imageNamed:@"0012.jpg"] forState:UIControlStateNormal];

}

- (void)backAction
{
    if (self.indexRow != 0) {
        self.indexRow --;
    } else {
        //返回最后一首
        [self setIndexRow:self.allMusicArray.count - 1];
    }
    
    self.navigationItem.title = [self.allMusicArray[self.indexRow] title];
    [self.imgView sd_setImageWithURL:[NSURL URLWithString:[self.allMusicArray[self.indexRow] coverLarge]]];
    [self.audioPlayer play:[self.allMusicArray[self.indexRow] playUrl64]];
    [self.playButton setImage:[UIImage imageNamed:@"0012.jpg"] forState:UIControlStateNormal];

}

- (void)setModel:(KHHMuscieModel *)model
{
    _model = model;
    [self playAction];
    [self.imgView sd_setImageWithURL:[NSURL URLWithString:self.model.coverLarge]];
    self.navigationItem.title = self.model.title;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
